<!--产品表单组件-->
<template>
  <div>
    <el-dialog 
      :title="isEditMode ? '修改产品' : '添加产品'" 
      :visible.sync="dialogVisible" 
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef" 
        :model="localFormData" 
        :rules="rules" 
        label-width="100px"
        size="mini"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="产品编码" prop="product_code">
              <el-input 
                v-model="localFormData.product_code" 
                placeholder="请输入产品编码"
                size="mini"
              >
                <el-button slot="append" icon="el-icon-search" @click="openProductSelector"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="product_name">
              <el-input 
                v-model="localFormData.product_name" 
                placeholder="请输入产品名称"
                size="mini"
                @blur="checkNameUnique"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="product_sfn">
              <el-input 
                v-model="localFormData.product_sfn" 
                placeholder="请输入规格型号"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input 
                v-model="localFormData.unit" 
                placeholder="请输入单位"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="最低检测数" prop="quantity_check_num">
              <el-input-number 
                v-model="localFormData.quantity_check_num" 
                :min="1"
                :precision="0"
                size="mini"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大不合格数" prop="quantity_unqualified_num">
              <el-input-number 
                v-model="localFormData.quantity_unqualified_num" 
                :min="0"
                :precision="0"
                size="mini"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="致命缺陷率" prop="cr_rate">
              <el-input-number 
                v-model="localFormData.cr_rate" 
                :min="0"
                :max="100"
                :precision="2"
                size="mini"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="严重缺陷率" prop="maj_rate">
              <el-input-number 
                v-model="localFormData.maj_rate" 
                :min="0"
                :max="100"
                :precision="2"
                size="mini"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轻缺陷率" prop="min_rate">
              <el-input-number 
                v-model="localFormData.min_rate" 
                :min="0"
                :max="100"
                :precision="2"
                size="mini"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="localFormData.remark" 
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
            size="mini"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleSubmit" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 产品选择对话框 -->
    <el-dialog
      title="选择产品"
      :visible.sync="productSelectorVisible"
      width="70%"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="filter-container">
        <el-input
          v-model="productQuery.keyword"
          placeholder="输入关键字搜索"
          style="width: 200px;"
          size="mini"
          clearable
          @keyup.enter.native="handleProductSearch"
        />
        <el-button type="primary" size="mini" icon="el-icon-search" @click="handleProductSearch">搜索</el-button>
      </div>
      
      <el-table
        v-loading="productLoading"
        :data="productList"
        border
        size="mini"
        style="width: 100%"
        height="350px"
        @row-click="handleProductRowClick"
        highlight-current-row
        ref="productTable"
      >
        <el-table-column prop="product_code" label="产品编码" width="120" />
        <el-table-column prop="product_name" label="产品名称" width="150" />
        <el-table-column prop="product_sfn" label="规格型号" width="120" />
        <el-table-column prop="product_unit" label="单位" width="80" />
        <el-table-column prop="product_type" label="产品类型" width="100" />
        <el-table-column prop="product_status" label="状态" width="80" />
        <el-table-column prop="remarks" label="备注" />
      </el-table>
      
      <div class="pagination-container">
        <!-- 替换原生分页组件，改为自定义按钮组 -->
        <div class="custom-pagination">
          <span>共 {{ productTotal }} 条</span>
          <el-select v-model="productQuery.pageSize" size="mini" style="width: 100px; margin: 0 10px;">
            <el-option v-for="size in [10, 20, 30, 50]" :key="size" :label="`${size}条/页`" :value="size"></el-option>
          </el-select>
          
          <el-button-group>
            <el-button 
              size="mini" 
              icon="el-icon-arrow-left" 
              :disabled="productQuery.pageNum <= 1"
              @click="handleManualPageChange(productQuery.pageNum - 1)"
            ></el-button>
            
            <el-button 
              v-for="page in displayPageNumbers" 
              :key="page"
              size="mini" 
              :type="page === productQuery.pageNum ? 'primary' : ''" 
              @click="handleManualPageChange(page)"
            >{{ page }}</el-button>
            
            <el-button 
              size="mini" 
              icon="el-icon-arrow-right" 
              :disabled="productQuery.pageNum >= totalPages"
              @click="handleManualPageChange(productQuery.pageNum + 1)"
            ></el-button>
          </el-button-group>
          
          <span style="margin-left: 10px;">
            前往 
            <el-input 
              v-model.number="jumpToPage" 
              size="mini" 
              style="width: 50px;" 
              @keyup.enter.native="handleJumpToPage"
            ></el-input>
            页
          </span>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="productSelectorVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmSelectProduct" :disabled="!selectedProduct">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  fetchProductList, 
  selectQcTemplateProductNameUnique, 
  insertTemplateDetail, 
  updateTemplateDetail 
} from '@/api/qc/QualitySchemeOrder'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEditMode: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({
        record_id: null,
        template_id: null,
        productId: null,
        productCode: '',
        productName: '',
        productSfn: '',
        unit: '',
        quantity_check_num: 1,
        quantity_unqualified_num: 0,
        cr_rate: 0,
        maj_rate: 0,
        min_rate: 100,
        remark: ''
      })
    }
  },
  data() {
    return {
      localFormData: JSON.parse(JSON.stringify(this.formData)),
      rules: {
        product_code: [
          { required: true, message: '请输入产品编码', trigger: 'blur' }
        ],
        product_name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { validator: this.validateNameUnique, trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ]
      },
      submitting: false,
      // 防抖定时器
      _validationTimer: null,
      productOptions: [],
      loading: false,
      
      // 产品选择器相关数据
      productSelectorVisible: false,
      productLoading: false,
      productList: [],
      productTotal: 0,
      selectedProduct: null,
      productQuery: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      
      // 分页相关
      jumpToPage: 1,
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    
    // 计算总页数
    totalPages() {
      return Math.max(1, Math.ceil(this.productTotal / this.productQuery.pageSize))
    },
    
    // 计算需要显示的页码
    displayPageNumbers() {
      const current = this.productQuery.pageNum
      const total = this.totalPages
      
      if (total <= 7) {
        // 如果总页数少于7，显示所有页码
        return Array.from({length: total}, (_, i) => i + 1)
      }
      
      // 否则显示部分页码
      if (current <= 4) {
        // 靠近开始的页码
        return [1, 2, 3, 4, 5, '...', total]
      } else if (current >= total - 3) {
        // 靠近结束的页码
        return [1, '...', total - 4, total - 3, total - 2, total - 1, total]
      } else {
        // 中间的页码
        return [1, '...', current - 1, current, current + 1, '...', total]
      }
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.localFormData = JSON.parse(JSON.stringify(this.formData))
          this.$nextTick(() => {
            if (this.$refs.formRef) {
              this.$refs.formRef.clearValidate()
            }
          })
        } else {
          // 关闭对话框时清除防抖定时器
          if (this._validationTimer) {
            clearTimeout(this._validationTimer)
            this._validationTimer = null
          }
        }
      }
    },
    'productQuery.pageNum': {
      handler(val) {
        console.log('监听到pageNum变化:', val)
        // 不在这里直接调用fetchProductListData避免重复调用
      }
    },
    'productQuery.pageSize': {
      handler(val) {
        console.log('监听到pageSize变化:', val)
        // 当每页条数变化时，返回第一页并重新加载数据
        this.productQuery.pageNum = 1
        this.fetchProductListData()
      }
    }
  },
  mounted() {
    // 确保分页事件正确绑定
    this.$nextTick(() => {
      if (this.$refs.productPagination) {
        console.log('分页组件已挂载，手动绑定事件')
        this.$refs.productPagination.$on('current-change', this.handleProductPageChange)
        this.$refs.productPagination.$on('size-change', this.handleProductSizeChange)
      }
    })
  },
  beforeDestroy() {
    // 组件销毁时清理定时器
    if (this._validationTimer) {
      clearTimeout(this._validationTimer)
      this._validationTimer = null
    }
  },
  methods: {
    // 检查名称唯一性
    async checkNameUnique() {
      try {
        const res = await selectQcTemplateProductNameUnique(this.localFormData.product_name)
        if (!res) {
          this.$message.warning('该产品名称已存在，请修改')
        }
      } catch (error) {
        console.error('验证名称唯一性失败:', error)
      }
    },
    
    // 验证名称唯一性
    validateNameUnique(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入产品名称'))
        return
      }
      
      // 在编辑模式下，如果名称没有修改，跳过验证
      if (this.isEditMode && this.formData.product_name === value) {
        callback()
        return
      }
      
      // 添加防抖机制
      if (this._validationTimer) {
        clearTimeout(this._validationTimer)
      }
      
      this._validationTimer = setTimeout(() => {
        selectQcTemplateProductNameUnique(value).then(res => {
          if (res) {
            callback()
          } else {
            callback(new Error('该产品名称已存在'))
          }
        }).catch((error) => {
          // 如果是重复提交错误，静默处理
          if (error.message && error.message.includes('重复提交')) {
            callback()
          } else {
            // 其他错误记录日志但允许通过
            console.error('验证名称唯一性失败:', error)
            callback()
          }
        })
      }, 300)
    },

    // 打开产品选择器
    openProductSelector() {
      this.productSelectorVisible = true
      this.productQuery.pageNum = 1
      this.productQuery.keyword = ''
      this.selectedProduct = null
      // 添加防抖，避免重复调用
      if (!this.productLoading) {
        this.fetchProductListData()
      }
      
      // 检查分页组件状态
      this.$nextTick(() => {
        if (this.$refs.productPagination) {
          console.log('分页组件状态检查:', {
            组件实例存在: !!this.$refs.productPagination,
            当前页: this.$refs.productPagination.internalCurrentPage,
            总页数: this.$refs.productPagination.internalPageCount,
            总条数: this.$refs.productPagination.internalTotal
          })
        } else {
          console.warn('分页组件未找到')
        }
      })
    },
    
    // 获取产品列表数据
    async fetchProductListData() {
      console.log('开始获取产品列表: 页码=', this.productQuery.pageNum, '每页条数=', this.productQuery.pageSize)
      try {
        this.productLoading = true
        const params = {
          pageNum: this.productQuery.pageNum,
          pageSize: this.productQuery.pageSize,
          keyword: this.productQuery.keyword
        }
        
        console.log('请求参数:', params)
        
        const response = await fetchProductList(params)
        console.log('API响应:', response)
        
        if (response && response.rows) {
          this.productList = response.rows
          this.productTotal = response.total || 0
          
          // 如果返回的数据为空，且不是第一页，则尝试回到上一页
          if (this.productList.length === 0 && this.productQuery.pageNum > 1) {
            console.warn('当前页无数据，尝试回到上一页')
            this.productQuery.pageNum = Math.max(1, this.productQuery.pageNum - 1)
            // 避免无限循环
            if (this.productQuery.pageNum === 1) {
              this.$message.info('没有找到匹配的数据')
            } else {
              this.fetchProductListData()
            }
            return
          }
        } else {
          this.productList = []
          this.productTotal = 0
          console.warn('未接收到有效的数据响应')
        }
        
        // 更新跳转页码为当前页
        this.jumpToPage = this.productQuery.pageNum
        
      } catch (error) {
        console.error('获取产品列表失败:', error)
        this.$message.error('获取产品列表失败: ' + error.message)
      } finally {
        this.productLoading = false
        console.log('完成获取产品列表: 总条数=', this.productTotal, '当前页数据=', this.productList.length)
      }
    },
    
    // 处理产品搜索
    handleProductSearch() {
      console.log('搜索触发: 关键词 =', this.productQuery.keyword)
      this.productQuery.pageNum = 1
      this.fetchProductListData()
    },
    
    // 处理产品分页大小变化
    handleProductSizeChange(val) {
      console.log('分页大小改变: pageSize =', val)
      // 直接从事件源获取值
      this.productQuery.pageSize = val || 10
      // 每次改变页大小时，回到第一页
      this.productQuery.pageNum = 1
      this.fetchProductListData()
    },
    
    // 处理产品分页页码变化
    handleProductPageChange(val) {
      console.log('页码改变: pageNum =', val)
      // 直接从事件源获取值
      this.productQuery.pageNum = val || 1
      this.fetchProductListData()
    },
    
    // 处理产品行点击
    handleProductRowClick(row) {
      this.selectedProduct = row
      // 设置当前行为选中状态
      this.$refs.productTable.setCurrentRow(row)
    },
    
    // 确认选择产品
    confirmSelectProduct() {
      if (!this.selectedProduct) {
        this.$message.warning('请先选择一个产品')
        return
      }
      
      // 填充产品相关字段
      this.localFormData.product_id = this.selectedProduct.product_id
      this.localFormData.product_code = this.selectedProduct.product_code
      this.localFormData.product_name = this.selectedProduct.product_name
      this.localFormData.product_sfn = this.selectedProduct.product_sfn
      this.localFormData.unit = this.selectedProduct.product_unit || ''
      
      this.productSelectorVisible = false
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) {
          return
        }
        
        try {
          this.submitting = true
          
          if (!this.localFormData.template_id) {
            this.$message.error('缺少模板ID，请确保从正确的位置打开此对话框')
            return
          }

          // 提交前验证名称唯一性（仅在名称有修改时验证）
          if (this.localFormData.product_name) {
            // 检查名称是否被修改
            const isNameChanged = this.isEditMode && 
              this.formData.product_name !== this.localFormData.product_name
            
            // 如果是新增模式，或者编辑模式下名称有修改，才进行唯一性验证
            if (!this.isEditMode || isNameChanged) {
              try {
                const isUnique = await selectQcTemplateProductNameUnique(this.localFormData.product_name)
                if (!isUnique) {
                  this.$message.error('该产品名称已存在，请修改后重试')
                  return
                }
              } catch (error) {
                console.error('验证名称唯一性失败:', error)
                // 如果验证失败，可以选择继续提交或提示用户
                // 这里选择继续提交，避免因为网络问题导致无法提交
              }
            }
          }
          
          let response
          if (this.isEditMode) {
            response = await updateTemplateDetail(this.localFormData)
          } else {
            response = await insertTemplateDetail(this.localFormData)
          }
          
          if (response && response.data) {
            this.$message.success(this.isEditMode ? '修改成功' : '添加成功')
            // 使用后端返回的数据，确保有正确的record_id
            const updatedData = this.isEditMode ? this.localFormData : {...this.localFormData, record_id: response.data}
            this.$emit('submit', updatedData)
            this.dialogVisible = false
          } else {
            throw new Error(response?.msg || '操作失败')
          }
        } catch (error) {
          console.error('提交失败:', error)
          this.$message.error('提交失败: ' + error.message)
        } finally {
          this.submitting = false
        }
      })
    },
    
    // 手动处理页码变化
    handleManualPageChange(page) {
      console.log('手动切换到页码:', page)
      if (typeof page === 'number' && page !== this.productQuery.pageNum) {
        this.productQuery.pageNum = page
        this.fetchProductListData()
      }
    },
    
    // 处理跳转到指定页
    handleJumpToPage() {
      const page = parseInt(this.jumpToPage)
      if (!isNaN(page) && page >= 1 && page <= this.totalPages && page !== this.productQuery.pageNum) {
        console.log('跳转到页码:', page)
        this.productQuery.pageNum = page
        this.fetchProductListData()
      }
      // 重置跳转框为当前页
      this.jumpToPage = this.productQuery.pageNum
    }
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 15px;
}

.filter-container {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 自定义分页样式 */
.custom-pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.custom-pagination .el-button-group {
  margin: 0 10px;
}

.custom-pagination .el-button {
  padding: 5px 10px;
  min-width: 32px;
}

/* 数字按钮 */
.custom-pagination .el-button-group .el-button {
  margin-left: -1px;
}
</style> 